package controllers

import (
	"encoding/json"
	"exp/cache"
	"exp/models"
	"exp/pkg"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
	"time"
)

type ExpController struct {
	beego.Controller
}

// 登录认证
func (c *ExpController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "字段不能为空",
		}
		c.ServeJSON()
		return
	}
	//判断密码是否错误三次-redis读取数据
	loginError_key := "login_error" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, loginError_key).Int()
	if errCount >= 3 {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "密码错误三次，禁止登录",
		}
		c.ServeJSON()
		return
	}
	//用户是否存在
	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "用户不存在",
		}
		c.ServeJSON()
		return
	}
	//判断密码
	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, loginError_key) //密码错误 redis的值+1
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, loginError_key, 3, time.Hour*1) //redis密码错误。设置为三
			c.Data["json"] = map[string]interface{}{
				"code": 0,
				"msg":  "密码错误三次",
			}
			c.ServeJSON()
			return
		}
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "密码错误",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	}
	c.ServeJSON()
	return
}

// 角色-权限 添加(角色分配权限)
func (c *ExpController) RoleNodeAdd() {
	rid, _ := c.GetInt("rid") //角色id
	nid, _ := c.GetInt("nid") //权限id

	data := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "添加成功",
			"data": data,
		}
		c.ServeJSON()
		return
	}
}

// 用户-角色
func (c *ExpController) UserRole() {
	uid, _ := c.GetInt("uid")

	var list models.Role
	err := models.DB.Table("roles").Joins("left join user_roles on user_roles.rid =roles.id").
		Where("user_roles=?", uid).Find(&list).Debug().Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "查询失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "查询成功",
			"data": list,
		}
		c.ServeJSON()
		return
	}

}

// 角色-权限
func (c *ExpController) RoleNode() {
	rid, _ := c.GetInt("rid")

	var list models.Node
	err := models.DB.Table("nodes").Joins("left join role_nodes on role_nodes.nid=nodes.id").
		Where("role_nodes.rid=?", rid).Find(&list).Debug().Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "查询失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "查询成功",
			"data": list,
		}
		c.ServeJSON()
		return
	}
}

//物流添加

func (c *ExpController) CompanyAdd() {
	name := c.GetString("name")
	comp := models.Comp{
		Name: name,
	}
	err := models.DB.Create(&comp).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "添加成功",
			"data": comp,
		}
		c.ServeJSON()
		return
	}
}

// 快递单添加
func (c *ExpController) OrderAdd() {
	order_no := c.GetString("order_no")
	cid, _ := c.GetInt("cid")
	eid, _ := c.GetInt("eid")
	data := models.Order{
		OrderNo: order_no,
		Cid:     cid,
		Eid:     eid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "添加成功",
			"data": order_no,
		}
		c.ServeJSON()
		return
	}
}

// 快递单列表
func (c *ExpController) OrderList() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 2)
	offset := (page - 1) * size

	var data []models.OrderListData

	order_list_key := "list_page" + strconv.Itoa(page)
	cacheList, _ := cache.Rdb.Get(cache.Ctx, order_list_key).Result()
	if cacheList == "" {
		models.DB.Table("orders").Joins("left join comps on orders.cid=comps.id").
			Joins("left join comps on comps.id = orders.cid").                                                          //关联企业表
			Joins("left join expresses on expresses.id = orders.eid").                                                  //关联快递表
			Select("orders.id as Id", "orders.order_no as OrdersNo", "comps.name as Cname", "expresses.name as Ename"). //查询的字段
			Offset(offset).Limit(size).
			Find(&data)
		cacheData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, order_list_key, cacheData, time.Hour*1)
	} else {
		json.Unmarshal([]byte(cacheList), &data)
	}

	var count int64
	models.DB.Table("orders").Count(&count)
	c.Data["json"] = map[string]interface{}{
		"code":  200,
		"msg":   "查询成功",
		"data":  data,
		"count": count,
	}
	c.ServeJSON()
	return
}

// 快递详情
func (c *ExpController) OrderDetail() {
	id, _ := c.GetInt("id", 0)
	if id == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "用户id为空",
		}
		c.ServeJSON()
		return
	}
	var order models.Order
	key := "detail_" + strconv.Itoa(id)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if cacheData == "" {
		models.DB.Where("id = ?", id).First(&order)
		cacheJson, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, key, cacheJson, time.Hour*1)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "查询成功",
		"data": order,
	}
	c.ServeJSON()
	return
}
